package com.ubs.training.server.dao.impl.jdbc;

import com.ubs.training.server.dao.ClientDao;
import com.ubs.training.server.dao.model.Client;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xubuntu
 * Date: 8/20/12
 * Time: 9:43 AM
 * To change this template use File | Settings | File Templates.
 */
public class NamedParamClientDaoImpl implements ClientDao {

    public static final String DELETE_FROM_CLIENT_WHERE_ID_ID = "delete from client where id=:id";
    DataSource ds;

    NamedParameterJdbcOperations ops;


    public DataSource getDs() {
        return ds;
    }

    public void setDs(DataSource ds) {
        this.ds = ds;
        ops = new NamedParameterJdbcTemplate(ds);
    }


    @Override
    public List<Client> getAll() {
        return ops.query("select id, fname, lname from client", Collections.EMPTY_MAP, new BeanPropertyRowMapper(Client.class));
    }

    @Override
    public Client getById(int id) {
        return ops.queryForObject("select id, fname, lname from client where id=:clientId", Collections.singletonMap("clientId", id), new BeanPropertyRowMapper<Client>(Client.class));
    }

    @Override
    public boolean add(Client client) {
        int id = ops.queryForInt("select next value for cmstr_seq from dual", Collections.EMPTY_MAP);
        client.setId(id);
        return  ops.update("insert into client values (:id, :fname, :lname)", new BeanPropertySqlParameterSource(client)) > 0;
    }

    @Override
    public boolean update(Client client) {
        return ops.update("update client set fname=:fname, lname=:lname where id=:id", new BeanPropertySqlParameterSource(client)) > 0;
    }

    @Override
    public boolean remove(Client client) {
        return ops.update(DELETE_FROM_CLIENT_WHERE_ID_ID, new BeanPropertySqlParameterSource(client)) > 0;
    }

    @Override
    public void remove(int clientId) {
        ops.update(DELETE_FROM_CLIENT_WHERE_ID_ID, Collections.singletonMap("id", clientId));
    }
}
